
import SwiftUI
import Charts

struct SleepQualityData: Identifiable {
    let id = UUID()
    let date: Date
    let qualityScore: Double // 0-100分
    var timeRange: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm"
        return formatter.string(from: date)
    }
}

struct SleepQualityChartView: View {
    let data: [SleepQualityData]
    private let maxScore: Double = 120
    
    var body: some View {
            Chart(data) { item in
                BarMark(
                    x: .value("时间", item.timeRange),
                    yStart: .value("最低分", item.qualityScore),
                    yEnd: .value("最高分", item.qualityScore+20),
                    width: .ratio(0.2)
                )
                .foregroundStyle(Color(hex: "#AC8FFF"))
            }
            .chartXAxis {
                AxisMarks(values: .automatic) { value in
                    AxisGridLine(
                        stroke: StrokeStyle(
                            lineWidth: 0.5,
                            dash: [0, 0])
                    )
                    .foregroundStyle(value.index == 0 ? Color(hex: "#C1C1C1"):
                                        Color.clear)
                    if let time = value.as(String.self) {
                        AxisValueLabel {
                            if value.index == 0{
                                Text("入睡\(time)")
                                    .foregroundStyle(Color(hex: "#C1C1C1"))
                                    .font(.system(size: 12))
                                    .frame(width: 100)
                                    .padding(.leading,20)
                            }else if value.index == data.count-1 {
                                Text("醒来\(time)")
                                    .foregroundStyle(Color(hex: "#C1C1C1"))
                                    .font(.system(size: 12))
                                    .frame(width: 100)
                                    .padding(.trailing,20)
                            }
                        }
                    }
                }
            }
            .chartYScale(domain: 0...maxScore)
            .chartYAxis {
                AxisMarks(position: .leading,values: .stride(by: 20)) { value in
                    AxisGridLine(
                        stroke: StrokeStyle(
                            lineWidth: 0.5,
                            dash: [4, 2])
                    )
                    .foregroundStyle(Color(hex: "#C1C1C1"))
                }
            }
            .frame(height: 200)
            .chartLegend(.hidden)
        }
}
